package com.lzx.applib.widget;

import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.Gravity;
import android.widget.TextView;

import com.lzx.applib.R;
import com.lzx.applib.utils.DpSpDip2Px;

/**
 * Created by Lzx on 16/11/14 0014.
 */
public class CircleSelectableText extends TextView {

    public static final String TAG = "CircleSelectableText";

    int selectedBg;
    int unselectedBg;
    int textSelectedColor;
    int textUnselectedColor;
    int strokeWidth;

    Paint selectPaint;
    Paint unselectPaint;

    public CircleSelectableText(Context context) {
        this(context, null);
    }

    public CircleSelectableText(Context context, AttributeSet attrs) {
        super(context, attrs);
        setGravity(Gravity.CENTER);

        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.CircleSelectableText);
        selectedBg = array.getColor(R.styleable.CircleSelectableText_selectedBg, Color.TRANSPARENT);
        unselectedBg = array.getColor(R.styleable.CircleSelectableText_unselectedBg, Color.TRANSPARENT);
        textSelectedColor = array.getColor(R.styleable.CircleSelectableText_textSelectedColor, Color.TRANSPARENT);
        textUnselectedColor = array.getColor(R.styleable.CircleSelectableText_textUnselectedColor, Color.TRANSPARENT);
        boolean selected = array.getBoolean(R.styleable.CircleSelectableText_selected, false);
        array.recycle();
        strokeWidth = DpSpDip2Px.getInstance().dip2px(1);

        setSelected(selected);
        selectPaint = new Paint();
        selectPaint.setColor(selectedBg);
        selectPaint.setAntiAlias(true);
        selectPaint.setStyle(Paint.Style.FILL_AND_STROKE);

        unselectPaint = new Paint();
        unselectPaint.setColor(unselectedBg);
        unselectPaint.setAntiAlias(true);
        unselectPaint.setStyle(Paint.Style.STROKE);
        unselectPaint.setStrokeWidth(strokeWidth);

        setBackgroundColor(Color.TRANSPARENT);
        setSelected(false);
    }

    @Override
    public void setSelected(boolean selected) {
        super.setSelected(selected);
        if (selected) {
            setTextColor(textSelectedColor);
        } else {
            setTextColor(textUnselectedColor);
        }
        invalidate();
    }

    @Override
    protected void onDraw(Canvas canvas) {
        float centerX = getWidth()/2f;
        float centerY = getHeight()/2f;

        float radiu = Math.min(centerX, centerY) - (isSelected() ? 0 : strokeWidth);
        canvas.drawCircle(centerX, centerY, radiu, isSelected() ? selectPaint : unselectPaint);

        super.onDraw(canvas);
    }
}
